﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;
using System.Threading;

namespace MailSender.Utils
{
	class MailRtns
	{
		public int MailCountTotal { get; set; }
		public int MailCountUnuque { get; set; }
		public int MailSent { get; set; }

		public delegate void OnMailSentDelegate(int mailCount, int mailSent);
		public delegate void OnMailSendingFinishedDelegate();

		public event OnMailSentDelegate OnMailSent;
		public event OnMailSentDelegate OnMailSending;
		public event OnMailSendingFinishedDelegate OnMailSendingFinished;

		private SmtpClient _smtpClient = null;
		private SmtpClient smtpClient { get { if (_smtpClient == null)_smtpClient = new SmtpClient(UserData.Current.mail_server, 587); return _smtpClient; } }

		private List<MailMessage> messagesToSend;

		public bool SendMailStart(List<MailMessage> messages)
		{
			this.messagesToSend = messages;

			System.Net.NetworkCredential cred = new System.Net.NetworkCredential(UserData.Current.mail_username, UserData.Current.mail_password);

			smtpClient.UseDefaultCredentials = false;
			smtpClient.EnableSsl = true;
			smtpClient.Credentials = cred;
			smtpClient.Port = 587;
			smtpClient.Timeout = 1200000;

			new Thread(SendAllMails) { Name = "SendMailThread" }.Start();
			return true;
		}


		private void SendAllMails()
		{
			try
			{
				this.MailCountTotal = this.messagesToSend.Count;
				this.MailSent = 0;

				int idx = 1;
				List<string> uniqueRecipients = new List<string>();

				for (int i = 0; i < this.messagesToSend.Count; i++)
				{
					System.Net.Mail.MailMessage mail = messagesToSend[i];

					if (uniqueRecipients.Contains(mail.To.ToString()))
					{
						idx++;
						uniqueRecipients.Clear();
					}

					uniqueRecipients.Add(mail.To.ToString());

					mail.Subject += string.Format(" ({0}/{1})", idx, this.MailCountUnuque);
					mail.Body = mail.Body + @"

--------------------
 Sent by MailSender
";
					if (OnMailSending != null)
						OnMailSending(MailCountTotal, MailSent);

					smtpClient.Send(mail);

					MailSent ++;

					if (OnMailSent != null)
						OnMailSent(MailCountTotal, MailSent);
				}

				if (OnMailSendingFinished != null)
					OnMailSendingFinished();
			}
			catch(Exception ex)
			{
				Cursor.Current = Cursors.Default;
			}
		}
	}
}
